#!/usr/bin/env perl

=head1 NAME

Util

=head1 SYNOPSIS

use Util;

=head1 DESCRIPTION

Provides some utility functions used by other modules. 'getCandidates' reads in the prospective candidate complexes for 
a query from the 'candidate' file. 'getDomains' loads the domains of a complex. 'writeResults' is a simple (and deprecated)
routine to write a set of subcomplexes to file.

=head1 REQUIRES

sbglib, PDL

=head1 AUTHOR

Philipp Harth <phil.harth@gmail.com>

=cut

package Util;

=head2 getCandidates

 Function: fetches pdbIDs of prospective candidate complexes
 Example : 
 Returns : list of candidate complexes (pdbIDs)
 Args    : path to candidates-file, query-pdbID
 
Fetches precomputed "best matches" for the query. Only these candidate complexes
will be searched for similarities with the query.   

=cut
sub getCandidates{
	my ($pathCandidates, $pdbID)= @_;
	my @candidates = ();
	open FILE, $pathCandidates or die "candidate file could not be opened";
	while(my $line=<FILE>){
		last if ($line =~ /---$pdbID---/);
	}
	if(my $line=<FILE>){
		my @columns = split(/ +/,$line);
		pop(@columns); #remove last element, which is "\n" and not a pdbID
		for my $column (@columns){
			$column =~ s/\n//;
			push @candidates, $column;
		}
	} else {
		die "$query pdbID not in precomputed candidate file";
	}
	close FILE; 	
	return @candidates;
}


=head2 getDomains

 Function: fetches domains of a complex
 Example : 
 Returns : list of domain objects
 Args    : pdb-ID, path to cofm-files
 
 Employs the DomainIO module of sbglib to fetch the domains of a complex as represented in cofm-format. 
 
=cut
sub getDomains{
	my ($pdbID, $pathCofm) = @_;
	#print $pdbID,"\n";
	my @doms = ();
	#determine file names that match to pdb-ID
	my $path = join '', $pathCofm, substr($pdbID, 1, 2), '/',$pdbID,'-*.cofm';
	my @files = < $path >; 
	#error if no files for pdbID are found
	my $errorMessage = join '',$pathCofm, substr($pdbID,1,2),'/';
	if (scalar(@files)==0){
		 die "ERROR: no cofm-file for $pdbID found in $errorMessage ";
	}
	#fetch domains
	for my $file (@files){
		my $io = SBG::DomainIO::cofm->new(file=>$file);
		while(my $dom = $io->read){
			push @doms, $dom;
		}
	}
	return @doms;
}

=head2 writeResults (deprecated)

 Function: writes results to file
 Example : 
 Returns : 
 Args    : reference to list of subcomplexes, query-PDB-ID, filepath, list of parameters
 
Writes a list of sucomplexes to file. (deprecated - use 'ResultWriter' instead)

=cut
sub writeResults{
	my ($subcomplexes, $query, $pathResult) = @_;
	my $file = join '','>>',$pathScores,"scores_",$query;
	open FILE, $file or die $!;
	for my $s (@{$subcomplexes}){
		for(my $i=0; $i<scalar(@{$s->domainsA}); $i++){
			print FILE (@{$s->domainsA}[$i]->id," <==> ",@{$s->domainsB}[$i]->id,$/);
		}
		print FILE ("RMSD: ", $s->rmsd," Total deviation: ",$s->deviation,$/);
		print FILE ("----------------------------------------------------------",$/);
	}
	close FILE;
}

1;